package com.bjb.vr.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.Objects;

/**
 * @description:
 * @author: HuJingBo
 * @time: 2022/3/16 14:21
 */
@Slf4j
public class ZkClientUtil {

    private ZkClientUtil() {
    }

    /**
     * 创建临时节点
     *
     * @param zkClient
     * @param path
     * @param data
     */
    public static boolean createTempNode(CuratorFramework zkClient, String path, String data) {
        try {
            Stat stat = zkClient.checkExists().forPath(path);
            if (Objects.nonNull(stat)) {
                zkClient.delete().forPath(path);
                log.info("【当前节点路径已存在,删除重建....】= {}", path);
            }
            String nodeInfo = zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, data.getBytes());
            log.info("【当前节点路径信息....】= {}", nodeInfo);
            return true;
        } catch (Exception e) {
            log.error("【创建临时节点异常】{},{},{}", path, data, e);
            return false;
        }
    }
}

